package oct2013.linkednode;

import java.util.ArrayList;

/**
 * @author Yinzi Chen
 * @date Nov 4, 2013
 */
public class MergekSortedLists {

    public ListNode mergeKLists(ArrayList<ListNode> lists) {
        if (lists.size() == 0)
            return null;
        return mergeKLists(lists, 0, lists.size() - 1);
    }

    ListNode mergeKLists(ArrayList<ListNode> lists, int l, int r) {
        if (l == r)
            return lists.get(l);
        int m = l + r >> 1;
        ListNode l1 = mergeKLists(lists, l, m);
        ListNode l2 = mergeKLists(lists, m + 1, r);
        return merge2Lists(l1, l2);
    }

    ListNode merge2Lists(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(0);
        ListNode cur = dummy;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                cur.next = l1;
                cur = l1;
                l1 = l1.next;
            } else {
                cur.next = l2;
                cur = l2;
                l2 = l2.next;
            }
        }
        while (l1 != null) {
            cur.next = l1;
            cur = l1;
            l1 = l1.next;
        }
        while (l2 != null) {
            cur.next = l2;
            cur = l2;
            l2 = l2.next;
        }
        return dummy.next;
    }
}
